package com.urban.pooling.service;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.urban.pooling.domain.RouteRequest;
import com.urban.pooling.domain.RouteRequestStatus;
import com.urban.pooling.domain.User;
import com.urban.pooling.repository.RouteRequestRepository;
import com.urban.pooling.repository.RouteRequestStatusRepository;

@Service
public class RouteRequestService {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

	@Autowired
	private RouteRequestRepository routeRequestRepo;

	@Autowired
	private RouteRequestStatusRepository routeReqStatusRepo;

	public RouteRequestStatus getRequestStatus(String status) {
		return routeReqStatusRepo.findByStatus(status);
	}

	public void save(RouteRequest request) {
		request.setCreationDate(new Date());
		routeRequestRepo.save(request);
	}

	public RouteRequest find(Integer id) {
		return routeRequestRepo.findOne(id);
	}

	public void updateStatus(Integer routeRequestId, String statusString) {
		RouteRequest routeRequest = routeRequestRepo.findOne(routeRequestId);
		if (routeRequest == null) {
			throw new IllegalArgumentException("RouteRequest does not exist");
		}
		if (routeRequest.getRouteRequestStatus().getStatus().equals(RouteRequestStatus.PENDING)) {
			RouteRequestStatus newStatus = routeReqStatusRepo.findByStatus(statusString);
			if (newStatus != null) {
				routeRequest.setRouteRequestStatus(newStatus);
				routeRequestRepo.save(routeRequest);
			}
		}

	}

	/**
	 * Returns a list of route requests made to the user and having the given
	 * status.
	 * 
	 * @param user
	 * @param status
	 */
	public Iterable<RouteRequest> find(User user, String status) {
		RouteRequestStatus rrStatus = routeReqStatusRepo.findByStatus(status);
		return routeRequestRepo.findForUserAndByStatus(user,status);
	}
}
